package com.sun.redis.controller;

import cn.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.SocketTimeoutException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping("/setKey")
    public String setKey(){
        redisTemplate.opsForValue().set("name","jack");
        return (String) redisTemplate.opsForValue().get("name");
    }
    @GetMapping("testLock")
    public void testLock(){
        UUID uuid = UUID.randomUUID();
        // 获取锁 setne
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3,TimeUnit.SECONDS);
        if (lock){
            //上锁成功
            Object value = redisTemplate.opsForValue().get("k1");
            if (StringUtils.isEmpty(value)){
                return;
            }
            int num = Integer.parseInt(value + "");
            redisTemplate.opsForValue().set("num",++num);
            if (uuid.equals(redisTemplate.opsForValue().get("lock"))) {
                Boolean lock1 = redisTemplate.delete("lock");
            }
            
        }else {

        }
        String s = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
    }


    @Resource
    RestTemplate restTemplate;

    @GetMapping("easyGet")
    @Retryable(value = {SocketTimeoutException.class,},maxAttempts = 3,backoff = @Backoff(delay = 1000))
    public void easyGet()  {
        String template = HttpUtil.get("http://127.0.0.1:80/springMvc/testSer", 1000);
        System.out.println(template);

    }

    public static void main(String[] args) {
        String s = HttpUtil.get("http://127.0.0.1:80/springMvc/testSer", 2000);
        System.out.println(s);
    }

}
